package com.task.util;

import java.util.Set;

import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.task.bean.annotation.TaskAnnotation;

/*
 * 类扫描工具
 */
public class ClassScanUtil {
   
	private Logger log=LoggerFactory.getLogger(ClassScanUtil.class);
	
	private static ClassScanUtil scanUtil;
    
    /**
       * 默认是TaskAnnotation的注解
     */
    private Set<Class<?>> taskcls=null;
    
	private ClassScanUtil() {}
	
	public static ClassScanUtil getClassScanUtil() {
		if(null==ClassScanUtil.scanUtil) {
			scanUtil=new ClassScanUtil();
			scanUtil.init();
		}
			return scanUtil;
	}
	
	private void init() {
		log.info("===扫描任务类开始");
		taskcls=this.getAnnotation("com.task.quartz",TaskAnnotation.class);
		log.info("===扫描任务类结束,任务个数:"+taskcls.size());
	}
	
	/**
	 * 获取注解下所有的类
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Set<Class<?>> getAnnotation(String path,Class cls){
		Reflections reflections = new Reflections(path);
        @SuppressWarnings("unchecked")
		Set<Class<?>> classes = reflections.getTypesAnnotatedWith(cls);
        return classes;
	}

	public Set<Class<?>> getTaskcls() {
		return taskcls;
	}
	
	/*
	 * 获取定时任务注解的类
	 */
	public Class getClass(String taskName) {
		if(null!=this.taskcls) {
			for(Class cls:taskcls) {
				TaskAnnotation task=(TaskAnnotation) cls.getAnnotation(TaskAnnotation.class);
				if(null!=task && task.value().equals(taskName)) {
				 return cls;
				}
			}
		}
		return null;
	}
}
